package com.bawei.room;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * @Author : yaotianxue
 * @Time : On 2023/9/15 09:18
 * @Description : AppDataBase
 */

/**
 * 数据库升级1-2：student表新增字段sex:integer
 * （1）version版本号
 * （2） 定义升级版本：MIGRATION_1_2
 * （3）addMigrations(MIGRATION_1_2)添加版本
 * （4）Student表新添加sex字段
 * 数据库升级2-3：student表修改字段sex：integer修改为text
 *
 */
//3：database数据库：entities表  version版本号,升级使用 exportSchema是否输出，升级使用
@Database(entities = {Student.class},version = 3,exportSchema = true)
public abstract class AppDataBase extends RoomDatabase {

    public static final String DB_NAME = "2104.db";//数据库的名字
    //注意构造不能私有化:单例
    private static AppDataBase appDataBase;
    public static AppDataBase getInstance(){//返回当前实例对象
        if(appDataBase == null){
            synchronized (AppDataBase.class){
                if(appDataBase == null){
                    appDataBase = Room.databaseBuilder(App.instance,AppDataBase.class,DB_NAME)
                            .allowMainThreadQueries()//默认不能在主线程中访问数据库
                            .addMigrations(MIGRATION_1_2)
                            .addMigrations(MIGRATION_2_3)
//                            .createFromAsset("init.db")
                            .build();
                }
            }
        }
        return appDataBase;
    }

    private StudentDao mStudentDao;
    //模板模式
    public abstract StudentDao getStudentDao();

    //升级1-2：新添加sex性别字段:int
    private static Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase supportSQLiteDatabase) {
            supportSQLiteDatabase.execSQL("ALTER TABLE student ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");
        }
    };

    //升级2-3：新添加sex性别字段:int
    private static Migration MIGRATION_2_3 = new Migration(2,3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //1：创建一张临时表
            database.execSQL("CREATE TABLE temp_student (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+
                    "username TEXT,"+
                    "age INTEGER NOT NULL,"+
                    "sex TEXT DEFAULT 'M')");
            //2：将旧表数据复制到临时表中
            database.execSQL("INSERT INTO temp_student (username,age,sex)" +
                    "SELECT username,age,sex FROM student");
            //3：将旧表删除
            database.execSQL("DROP TABLE student");
            //4：临时表重命名
            database.execSQL("ALTER TABLE temp_student RENAME TO student");
        }
    };



}
